<template>
  <div style="padding: 30px">
    <el-card>
      <div style="margin-bottom: 20px">
        <el-button type="primary" @click="formShow()">新增内容</el-button>
        <el-button type="danger" style="float: right" @click="delMenuClick()"
          >删除菜单</el-button
        >
        <el-button type="primary" style="float: right" @click="changeClick()"
          >编辑菜单</el-button
        >
      </div>
      <el-table :data="tableData" border style="width: 100%">
        <el-table-column fixed type="index" :index="indexMethod" />
        <el-table-column fixed label="所属分类" width="150" align="center">
          <template>
            {{ belongState }}
          </template>
        </el-table-column>
        <el-table-column fixed prop="title" label="标题">
          <template slot-scope="scope">
            <!-- 2置顶 -->

            <span
              v-if="scope.row.top === 2"
              style="color: red; margin-right: 5px"
              >[顶]</span
            >
            <span>{{ scope.row.title }}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="publishTime"
          label="发布日期"
          width="120"
          align="center"
        >
          <template slot-scope="scope">
            <span v-if="scope.row.publishTime">{{
              returnDay(scope.row.publishTime)
            }}</span>
            <span v-else>--</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="state"
          label="发布时间"
          width="120"
          align="center"
        >
          <template slot-scope="scope">
            <span v-if="scope.row.publishTime">
              {{ returnTime(scope.row.publishTime) }}</span
            >
            <span v-else>--</span>
          </template>
        </el-table-column>
        <el-table-column prop="state" label="状态" width="120" align="center">
          <template slot-scope="scope">
            <span v-if="scope.row.state === 1">隐藏</span>
            <span v-else>显示</span>
          </template>
        </el-table-column>
        <!-- <el-table-column prop="top" label="是否置顶" width="120">
          <template slot-scope="scope">
            <span v-if="scope.row.top === 1">不置顶</span>
            <span v-else>置顶</span>
          </template>
        </el-table-column> -->
        <el-table-column fixed="right" label="操作" width="200" align="center">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="primary"
              @click="handleClick(scope.row)"
              >编辑</el-button
            >
            <el-button size="mini" type="danger" @click="delClick(scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        :page-size="10"
        layout="total, pager, next, jumper"
        :current-page="query.pageNo + 1"
        :total="query.total"
        @current-change="handleCurrentChange"
      />
    </el-card>
    <el-dialog
      :title="contentAddForm.id ? '编辑' : '新增'"
      :visible.sync="dialogFormVisible"
      width="90%"
    >
      <el-form
        ref="contentAddForm"
        :rules="rules"
        :model="contentAddForm"
        label-width="120px"
      >
        <el-form-item label="标题">
          <el-input v-model="contentAddForm.title" autocomplete="off" />
        </el-form-item>
        <el-form-item label="是否置顶">
          <el-radio-group v-model="contentAddForm.top">
            <el-radio :label="1">不置顶</el-radio>
            <el-radio :label="2">置顶</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="状态">
          <el-radio-group v-model="contentAddForm.state">
            <el-radio :label="1">隐藏</el-radio>
            <el-radio :label="2">显示</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item
          v-if="contentAddForm.state === 1"
          label="设置显示时间"
          prop="publishTime"
        >
          <el-date-picker
            v-model="contentAddForm.publishTime"
            value-format="timestamp"
            type="datetime"
            placeholder="选择日期时间"
          />
        </el-form-item>
        <el-form-item label="上传文件">
          <el-upload
            v-if="dialogFormVisible"
            class="imgBox"
            :limit="1"
            action="https://jsonplaceholder.typicode.com/posts/"
            :file-list="fileList"
            :http-request="handleUploadImg"
            :on-remove="handleRemove"
          >
            <el-button type="primary">点击上传</el-button>
          </el-upload>
          <el-form-item
            v-if="contentAddForm.content && contentAddForm.id"
            label=""
          />
          <el-button
            v-if="contentAddForm.content && contentAddForm.id"
            type="success"
            style="margin-top: 10px"
            ><a :href="contentAddForm.content">点击下载</a></el-button
          >
          <!-- </el-form-item>
          <el-input
            v-if="contentAddForm.id"
            v-model="contentAddForm.content"
            style="margin-top: 10px"
            type="text"
            disabled
          />
        </el-form-item> -->
        </el-form-item></el-form
      >
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelClick('contentAddForm')">取 消</el-button>
        <el-button type="primary" @click="submitForm('contentAddForm')"
          >确 定</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { setMenuObj, getMenuObj, removeMenuObj } from '@/utils/auth' // get token from cookie
import {
  addContent,
  delContent,
  updateContent,
  listContent,
  detailContent,
  delSubMenu
} from '@/api/content' // get token from cookie
import dayjs from 'dayjs'
import Tinymce from '@/components/Tinymce'

import Oss from '@/utils/oss'
// import { getStsToken } from '@/utils/auth'
export default {
  components: { Tinymce },
  data() {
    return {
      dialogFormVisible: false,
      query: {
        pageNo: 0,
        pageSize: 10,
        menuId: '',
        state: 0,
        total: 0
      },
      pageInfo: {},
      rules: {
        publishTime: [
          { required: true, message: '请选择发布时间', trigger: 'blur' }
        ], // 发布时间
        title: [{ required: true, message: '请输入活', trigger: 'blur' }] // 标题
      },
      contentAddForm: {
        content: '', // 内容
        publishTime: +new Date(), // 发布时间
        state: 1, //  1 显示（默认）  3隐藏
        title: '', // 标题
        top: 1 // 置顶    1不置顶 （默认）   2置顶
      },
      fileList: [],
      tableData: [],
      oss: {},
      stsToken: {
        accessKeyId: 'LTAI5tCQiELrNuXxFdf5wyuB',
        accessKeySecret: 'VlsN1KXHj4RV709wAOIHOnzjn9Qbke',
        bucket: 'utopia9527',
        region: 'oss-cn-shanghai'
      },
      belongState: ''
    }
  },
  created() {
    // /companyWeb/content/list?pageNo=0&pageSize=4&menuId=2&state=1
    this.oss = new Oss(this.stsToken, window)
    this.oss.__init__()
    this.pageInfo = getMenuObj()
    // this.query.subMenuId = this.pageInfo.id
    this.query.menuId = this.pageInfo.parentId
    this.belongState = this.pageInfo.meta.title
    console.log(this.query)
    this.getList()
  },
  methods: {
    changeClick(item) {
      this.$router.push({
        name: 'itemEdit'
      })
    },

    handleUploadImg(param) {
      console.log(param)
      this.oss.__main__('activity', 'uploadImg', param).then((res) => {
        if (res.res.status === 200) {
          this.$message.success('上传成功')
          console.log(res)
          this.contentAddForm.content =
            res.res.requestUrls[0].split('?uploadId=')[0]
          this.fileList = [
            {
              name: res.res.requestUrls[0].split('?uploadId=')[0],
              url: res.res.requestUrls[0].split('?uploadId=')[0]
            }
          ]
        }
      })
    },
    handleRemove(file, fileList) {
      console.log(this.fileList)
    },
    formShow() {
      this.dialogFormVisible = true
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          console.log(this.contentAddForm)
          const config = Object.assign({}, this.contentAddForm, {
            publishTime:
              this.contentAddForm.state === 1
                ? this.contentAddForm.publishTime
                : +new Date(),
            menuId: this.query.menuId
          })
          console.log(this.contentAddForm)
          if (this.contentAddForm.id) {
            updateContent(config).then((res) => {
              if (res.code === 1) {
                this.$message.success('操作成功')
                this.dialogFormVisible = false
                this.init()
                this.getList()
              }
            })
          } else {
            addContent(config).then((res) => {
              if (res.code === 1) {
                this.$message.success('操作成功')
                this.dialogFormVisible = false
                this.init()
                this.getList()
              }
            })
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    cancelClick(formName) {
      this.init(formName)
      this.$refs[formName].resetFields()
      this.dialogFormVisible = false
    },
    init(formName) {
      this.contentAddForm = {
        content: '', // 内容
        image: '', // 缩略图
        menuId: 0,
        publishTime: '', // 发布时间
        recap: '', // 摘要
        state: 1, //  1 显示（默认）  3隐藏
        subMenuId: '',
        title: '', // 标题
        top: 1 // 置顶    1不置顶 （默认）   2置顶
      }
      this.fileList = []
    },
    getList() {
      listContent(this.query).then((res) => {
        this.tableData = res.obj.data
        this.query.total = res.obj.count
      })
    },
    returnTime(item) {
      return dayjs(item).format('HH:mm:ss')
    },
    returnDay(item) {
      return dayjs(item).format('YYYY-MM-DD')
    },
    handleClick(item) {
      detailContent({ id: item.id }).then((res) => {
        this.contentAddForm = Object.assign({}, res.obj, {
          id: item.id
        })
        // const ossConfig = {
        //   expires: 3600,
        //   process: 'image/auto-orient,1/quality,q_90/format,src'
        // }
        // const url = this.oss.__main__(res.obj.image, 'readImg', ossConfig)
        if (res.obj.image) {
          this.fileList = [
            {
              name: res.obj.image,
              url: res.obj.image
            }
          ]
        }
        this.dialogFormVisible = true
      })
    },
    delClick(item) {
      this.$confirm('此操作将删除该信息, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          delContent({ id: item.id }).then((res) => {
            if (res.code === 1) {
              this.$message({
                type: 'success',
                message: '删除成功!'
              })
              this.getList()
            }
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    delMenuClick() {
      this.$confirm('此操作将删除该信息, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          delSubMenu({ id: this.query.subMenuId }).then((res) => {
            if (res.code === 1) {
              this.$message({
                type: 'success',
                message: '删除成功!'
              })
              setTimeout(() => {
                this.$router.push({
                  path: '/dashboard'
                })
                location.reload()
              }, 1000)
            }
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    // delMenuClick() {
    //   this.$confirm('此操作将删除该菜单, 是否继续?', '提示', {
    //     confirmButtonText: '确定',
    //     cancelButtonText: '取消',
    //     type: 'warning'
    //   }).then(() => {
    //     console.log(this.query.subMenuId)
    //     delSubMenu({ id: this.query.subMenuId }).then((res) => {
    //       if (res.code === 1) {
    //         this.$message({
    //           type: 'success',
    //           message: '删除成功!'
    //         })
    //       }
    //     })
    //   })
    // },
    indexMethod(index) {
      return this.query.pageNo * this.query.pageSize + (index + 1)
    },
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`)
    },
    handleCurrentChange(val) {
      this.query.pageNo = val - 1
      this.getList()
      console.log(`当前页: ${val}`)
    }
  }
}
</script>
